<?php

/* USER_FILE_NAME has this structure:
 * 
 * {
 *   "username': md5("password"),
 *   "anotherUsername': md5("password")
 * }
 *
 *
 * SAVE_FILE_NAME has this structure:
 *
 * {
 *   "username": {
 *     "sectors": {
 *       "name": "data"
 *     },
 *     "pricelists": {
 *       "name": "data"
 *     }
 *   }
 * }
 *
 */

require_once('../config.php');
require_once('./messages.php');

if(!file_exists("lock"))
  file_put_contents("lock", "");

if(!file_exists(SAVE_FILE_NAME))
  file_put_contents(SAVE_FILE_NAME, '<?php {} ?>');

if(!file_exists(USER_FILE_NAME))
  file_put_contents(USER_FILE_NAME, '<?php {} ?>');

$FileLock = fopen("lock", "r"); // Get a lock on the users and saves files
flock($FileLock, LOCK_EX);

function _RawSend($data)
{
  print json_encode($data);
  Close();
  die();
}

function Send($data = array())
{
  $data['Status'] = STATUS_OK;
  _RawSend($data);
}

function SendLoginFailed($data = array())
{
  $data['Status'] = STATUS_LOGIN_FAILED;
  _RawSend($data);
}

function SendCorrupt($data = array())
{
  $data['Status'] = STATUS_CORRUPT;
  _RawSend($data);
}

function SendError($error, $data = array())
{
  $data['Status'] = STATUS_ERROR;
  $data['Error'] = $error;
  _RawSend($data);
}

// This functions NEEDS to be run on close to allow other instances to run
function Close()
{
  global $FileLock;

  fclose($FileLock);
}

function ReadUsers()
{
  $text = file_get_contents(USER_FILE_NAME);
  $json = json_decode(str_replace('<?php ', '', str_replace(' ?>', '', $text)), true);

  return $json;
}

function ReadSaves()
{

  $text = file_get_contents(SAVE_FILE_NAME);
  $json = json_decode(str_replace('<?php ', '', str_replace(' ?>', '', $text)), true);

  return $json;
}

function WriteUsers($json)
{
  $text = json_encode($json);
  $text = "<?php $text ?>";   // Protect data

  file_put_contents(USER_FILE_NAME, $text);
}

function WriteSaves($json)
{
  $text = json_encode($json);
  $text = "<?php $text ?>";

  file_put_contents(SAVE_FILE_NAME, $text);
}

function VerifyUser($username, $password)
{
  $username = strtolower($username);

  // First, load the users.
  $users = ReadUsers();

  // Does the user exist?
  if(!isset($users[$username]))
  {
    throw new Exception('Unknown User');
  }

  else
  {
    $storedPassword = $users[$username];

    if($storedPassword != $password) // Check password
      throw new Exception('Incorrect Password');
  }
}

function AddUser($username, $password)
{
  $username = strtolower($username);

  $users = ReadUsers();

  if(isset($users[$username]))
    throw new Exception('Username Not Available');

  $saves = ReadSaves();

  $users[$username] = $password;
  $saves[$username] = array('sectors' => array(), 'pricelists' => array());

  WriteUsers($users);
  WriteSaves($saves);
}

function DeleteUser($username)
{
  $username = strtolower($username);

  $users = ReadUsers();
  $saves = ReadSaves();

  unset($users[$username]);
  unset($saves[$username]);

  WriteUsers($users);
  WriteSaves($saves);
}

function GetSectors($username)
{
  $saves = ReadSaves();

  return $saves[$username]['sectors'];
}

function GetPricelists($username)
{
  $saves = ReadSaves();

  return $saves[$username]['pricelists'];
}

function GetSector($username, $name)
{
  $saves = ReadSaves();

  if(!isset($saves[$username]['sectors'][$name]))
    throw new Exception('Does Not Exist');

  return $saves[$username]['sectors'][$name];
}

function GetPricelist($username, $name)
{
  $saves = ReadSaves();

  if(!isset($saves[$username]['pricelists'][$name]))
    throw new Exception('Does Not Exist');

  return $saves[$username]['pricelists'][$name];
}

function AddSector($username, $name, $data)
{
  $saves = ReadSaves();
  $sectors = &$saves[$username]['sectors'];

  if(isset($sectors[$name]))
    throw new Exception('Sector Already Exists');

  if(count($sectors) >= MAX_SAVED_SECTORS)
    throw new Exception('Exceeded Quota');

  $sectors[$name] = $data;

  WriteSaves($saves);
}

function AddPricelist($username, $name, $data)
{
  $saves = ReadSaves();
  $pricelists = &$saves[$username]['pricelists'];

  if(isset($pricelists[$name]))
    throw new Exception('Pricelist Already Exists');

  if(count($pricelists) >= MAX_SAVED_PRICELISTS)
    throw new Exception('Exceeded Quota');

  $pricelists[$name] = $data;

  WriteSaves($saves);

  return true;
}

function UpdateSector($username, $name, $data)
{
  $saves = ReadSaves();
  $sectors = &$saves[$username]['sectors'];

  if(!isset($sectors[$name]))
    throw new Exception('Does Not Exist');

  $sectors[$name] = $data;

  WriteSaves($saves);
}

function UpdatePricelist($username, $name, $data)
{
  $saves = ReadSaves();
  $pricelists = &$saves[$username]['pricelists'];

  if(!isset($pricelists[$name]))
    throw new Exception('Does Not Exist');

  $pricelists[$name] = $data;

  WriteSaves($saves);
}

function DeleteSector($username, $name)
{
  $saves = ReadSaves();

  unset($saves[$username]['sectors'][$name]);

  WriteSaves($saves);
}

function DeletePricelist($username, $name)
{
  $saves = ReadSaves();

  unset($saves[$username]['pricelists'][$name]);

  WriteSaves($saves);
}

function RenameSector($username, $oldName, $newName)
{
  $saves = ReadSaves();

  $sectors = &$saves[$username]['sectors'];

  if(!isset($sectors[$oldName]))
    throw new Exception('Does Not Exist');

  $sectors[$newName] = $sectors[$oldName];
  unset($sectors[$oldName]);

  WriteSaves($saves);
}

function RenamePricelist($username, $oldName, $newName)
{
  $saves = ReadSaves();

  $pricelists = &$saves[$username]['pricelists'];

  if(!isset($pricelists[$oldName]))
    throw new Exception('Does Not Exist');

  $pricelists[$newName] = $pricelists[$oldName];
  unset($pricelists[$oldName]);

  WriteSaves($saves);
}

function GetSectorCode($name)
{
  $sectors = json_decode(file_get_contents('sectors.js'), true);

  if(!isset($sectors[$name]))
    throw new Exception('Does Not Exist');

  return $sectors[$name];
}

function GetName($data)
{
  preg_match('/"name":"([a-zA-Z0-9 -]*)"/', $data, $matches);
  return $matches[1];
}

function ExtractMap($code)
{
  preg_match('/"map":"([a-zA-Z0-9 -]*)"/', $code, $matches);
  return $matches[1];
}

?>